package com.ning.city.controller;

import com.ning.city.bean.Token;
import com.ning.city.bean.User;
import com.ning.city.dto.UserDto;
import com.ning.city.service.UserService;
import com.ning.city.vo.CommonResult;
import com.ning.city.vo.PageData;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;

/**
 * @author Ning 242741154@qq.com
 * @date 2021/1/5 10:28
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/register")
    public CommonResult<User> register(@RequestBody @Validated UserDto.Register dto) {
        User user = userService.register(dto);
        CommonResult<User> result = new CommonResult<>();
        result.setData(user);
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/login")
    public CommonResult<Token> login(@RequestBody @Validated UserDto.Login dto) {
        return userService.login(dto);
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/delete")
    public CommonResult<Boolean> delete(String userId) {
        return new CommonResult<>(userService.delete(userId));
    }

    @RequestMapping(method = RequestMethod.POST, path = "/page")
    public CommonResult<PageData<User>> page(@RequestBody @Validated UserDto.PageInfo dto) {
        return new CommonResult<>(userService.getPageData(dto));
    }

    @RequestMapping(method = RequestMethod.PUT, path = "/updateName")
    public CommonResult<Boolean> updateName(@RequestBody @Validated UserDto.UpdateName dto) {
        return new CommonResult<>(userService.updateName(dto));
    }

    @RequestMapping(method = RequestMethod.PUT, path = "/updatePassword")
    public CommonResult<Boolean> updateName(@RequestBody @Validated UserDto.UpdatePassword dto) {
        final String msg = userService.updatePassword(dto);
        if (msg == null) {
            return new CommonResult<>(true);
        }
        final CommonResult<Boolean> result = new CommonResult<>();
        result.setErrors(Collections.singletonList(msg));
        return result;
    }
}


